const util = require('../../utils/util.js');
const {
  $Toast
} = require('../..//dist/base/index');
var interval;

Page({
  data: {
    userInfo: {},
    labels: 'Node',
    value: '',
    article_img: [],
    file_type: [],
    article_content: [''],
    content: {
      labels: '原创'
    },
    tip: '文件上传中',
    loadding: false,
    text_flag: true,
    labelIndex: 3,
    error: '',
    showActionsheet: false,
    actions: [{
        text: '图片',
        value: 1
      },
      {
        text: '视频',
        value: 2
      }
    ],
    isShowDelSheet: false,
		show: false,
		updateActions: [
			{
				index: 0,
				name: '更换'
			},
			{
				index: 1,
				name: '删除',
				subname: '操作无法撤销',
			}
		]
  },

	updateFile: function(e) {
		this.setData({ 
			show: true,
			location_index: e.currentTarget.dataset.index
		});
	},

	onClose() {
		this.setData({ show: false });
	},

	onSelect(event) {
		this.onClose();
		if(event.detail.index == 0) {
			//更换插图
			this.setData({
      showActionsheet: true
    });
		}
		if (event.detail.index == 1) {
			//删除插图
			var article_img = this.data.article_img;
			var file_type = this.data.file_type;
			article_img[this.data.location_index] = '/images/plus.png';
			file_type[this.data.location_index] = 1;
			this.setData({
				article_img: article_img,
				file_type: file_type,
				location_index: null
			});
		}
	},

  close: function() {
    this.setData({
      showActionsheet: false
    });
  },

  btnClick(e) {
    //选择图片上传
    if (e.detail.index == 0) {
      this.selected_img();
    }

    //选择视频上传
    if (e.detail.index == 1) {
      this.selected_video();
    }

    //关闭actionsheet弹框
    this.close();
  },

  onShow: function() {
    var that = this;
    interval = setInterval(function() {
      that.authSaveArticle();
    }, 1000 * 30);
  },

  authSaveArticle: function(e) {
    var that = this;
    if (!this.data.content.title || !this.data.content.author || !this.data.content.labels || !this.data.article_content || !this.data.content.openid) {
      that.setData({
        error: '填写标题触发定时保存草稿功能'
      });
    } else {
			var file_type = this.data.file_type || [];
			if(file_type.length == 0) {

			}
			for (var i = 0; i < this.data.article_img.length; i++) {
				if(!file_type[i]) {
					file_type[i] = 1;
				}
			}
			this.setData({file_type: file_type});
      var param = {
        title: this.data.content.title,
        author: this.data.content.author,
        labels: this.data.content.labels,
        openid: this.data.content.openid,
        avatar: this.data.userInfo.avatar,
        article_content: this.data.article_content.join('==='),
        article_img: this.data.article_img.join('==='),
				file_type: this.data.file_type.join('==='),
        app_sid: 'nyl'
      };

      //保存文章到草稿箱
      wx.request({
        url: util.basePath + '/article/v1/saveDraftContent',
        method: "post",
        data: param,
        header: {
          'content-type': 'application/json'
        },
        success(res) {
          if (res.data.status == 200) {
						if (e && e.currentTarget.dataset.index == 1) {
							$Toast({
								content: '保存草稿成功',
								type: 'default'
							});
						}
            that.setData({
              error: ''
            });
          } else {
            that.setData({
              error: res.data.err
            });
          }
        }
      });
    }
  },

  bindLabelChange: function(e) {
    if (this.data.labels[e.detail.value] == '公告' && this.data.userInfo.account != '19942706025') {
      $Toast({
        content: '未获得权限',
        type: 'error'
      });
    } else {
      this.setData({
        labelIndex: e.detail.value,
        ['content.labels']: this.data.labels[e.detail.value]
      });
    }
  },

  onLoad: function(options) {
    this.getCategories();
  },

  onHide: function() {
    wx.removeStorage({
      key: 'alterArticle',
      success: function(res) {

      },
    });
    wx.removeStorage({
      key: 'isEdit',
      success: function(res) {

      },
    });

    clearInterval(interval);
  },

  onUnload: function() {
    wx.removeStorage({
      key: 'alterArticle',
      success: function(res) {

      },
    });
    wx.removeStorage({
      key: 'isEdit',
      success: function(res) {

      },
    });
    clearInterval(interval);
  },

  getCategories: function() {
    var that = this;
    var userInfo = wx.getStorageSync("loginInfo");

    if (!userInfo) {
      $Toast({
        content: '请先登录!',
        type: 'error'
      });
      wx.reLaunch({
        url: '/pages/userinfo/userinfo',
      });
    } else {
      var alterArticle = wx.getStorageSync("alterArticle");
			console.log(alterArticle.file_type);

      if (alterArticle) {
        that.setData({
          userInfo: userInfo,
          ['content.author']: userInfo.username,
          ['content.openid']: userInfo.openid,
          ['content.title']: alterArticle.title,
          ['content.id']: alterArticle.id,
          labels: [alterArticle.labels],
          article_img: alterArticle.article_img,
          article_content: alterArticle.article_content,
					file_type: alterArticle.file_type
        });
      } else {
        //如果非修改文章，则判断是否为编辑状态
        var is_edit = wx.getStorageSync("isEdit");
        if (is_edit) {
          //文章处于编辑草稿状态，查询文章详情
          wx.request({
            url: util.basePath + '/article/v1/getDraftContentDetail',
            method: "post",
            data: {
              openid: wx.getStorageSync("loginInfo").openid,
              app_sid: wx.getStorageSync("loginInfo").app_sid
            },
            header: {
              'content-type': 'application/json'
            },
            success(res) {
              if (res.data.status == 200) {
                var article = res.data.payload;
                article.article_content = article.article_content.split('===');
                article.article_img = article.article_img.split('===');
								article.file_type = article.file_type.split('===');
                that.setData({
                  userInfo: userInfo,
                  ['content.author']: userInfo.username,
                  ['content.openid']: userInfo.openid,
                  ['content.title']: article.title,
                  ['content.id']: article.id,
                  labels: [article.labels],
                  article_img: article.article_img,
                  article_content: article.article_content,
									file_type: article.file_type
                });
              } else {
                $Toast({
                  content: res.data.err,
                  type: 'error'
                });
              }
            }
          });
        } else {
          //创作新文章
          this.setData({
            userInfo: userInfo,
            ['content.author']: userInfo.username,
            ['content.openid']: userInfo.openid
          });
        }
      }

      wx.request({
        url: util.basePath + '/article/v1/categories',
        method: "post",
        data: {},
        header: {
          'content-type': 'application/json'
        },
        success(res) {
          if (res.data.status == 200) {

            var labels = [];
            res.data.payload.forEach(label => {
              labels.push(label.labels);
            });
            that.setData({
              labels: labels
            });
          } else {
            $Toast({
              content: res.data.err,
              type: 'error'
            });
          }
        }
      });
    }
  },

  getSelectLabels: function(e) {
    this.setData({
      ['content.labels']: e.detail
    });
  },

  selected_video: function() {
    var that = this;
    wx.chooseVideo({
      sourceType: ['album', 'camera'],
      maxDuration: 60,
      camera: 'back',
      success: function(res) {
        var tempFilePaths = res.tempFilePath;

        that.setData({
          loading: true,
          increase: false
        });

        wx.uploadFile({
          url: util.basePath + '/users/upload_video',
          filePath: tempFilePaths,
          name: 'mp4_url',
          headers: {
            'Content-Type': 'form-data'
          },

          success: function(res) {
            if (res.statusCode == 413) {
              that.setData({
                loading: false
              });

              $Toast({
                content: '视频过大，请重新上传',
                type: 'error'
              });
            } else {
              that.setData({
                loading: false
              });

              var result = JSON.parse(res.data);
              if (result.status == 200) {
                //如果article_img是默认图片，则article_img置空
                var article_img = that.data.article_img;
                var file_type = that.data.file_type;
								var article_content = that.data.article_content || [];
								article_img[that.data.location_index] ? article_img[that.data.location_index] = result.payload : article_img.push(result.payload);
								file_type[that.data.location_index] ? file_type[that.data.location_index] = 2 : file_type.push(2);
								article_content[that.data.location_index] ? '' : article_content.push('');

                that.setData({
                  article_img: article_img,
									file_type: file_type,
									article_content: article_content,
									location_index: null
                });
              } else {
                $Toast({
                  content: result.err,
                  type: 'error'
                });
              }
            }
          }
        });
      }
    });
  },

  selected_img: function() {
    var that = this;
		
    wx.chooseImage({
      success(res) {
        const tempFilePaths = res.tempFilePaths;

        that.setData({
					showActionsheet: false,
          loading: true
        });

        wx.uploadFile({
          url: util.basePath + '/users/upload_avatar',
          filePath: tempFilePaths[0],
          name: 'avatar',
          success(res) {
            that.setData({
              loading: false
            });
            var result = JSON.parse(res.data);
            if (result.status == 200) {
              //如果article_img是默认图片，则article_img置空
              var article_img = that.data.article_img || [];
							var file_type = that.data.file_type || [];
							var article_content = that.data.article_content || [];
							article_img[that.data.location_index] ? article_img[that.data.location_index] = result.payload.avatar_path : article_img.push(result.payload.avatar_path);
							file_type[that.data.location_index] ? file_type[that.data.location_index] = 1 : file_type.push(1);
							article_content[that.data.location_index] ? '' : article_content.push('');

              that.setData({
                article_img: article_img,
								file_type: file_type,
								article_content: article_content,
								location_index: null
              });
            } else {
							console.log(result.err);
              $Toast({
                content: result.err,
                type: 'error'
              });
            }
          }
        });
      }
    });
  },

  upload_img: function(e) {
    var that = this;

    this.setData({
      showActionsheet: true
    });
  },

  titleInput: function(e) {
    this.setData({
      ['content.title']: e.detail.value
    });
  },

  textInput: function(e) {
    this.setData({
      ['content.content']: e.detail.value
    });
  },

  setContent: function(e) {
    var that = this;

    wx.request({
      url: util.basePath + '/users/text_define',
      method: "post",
      data: {
        text: e.detail.value
      },
      header: {
        'content-type': 'application/json'
      },
      success(res) {
        if (res.data.status == 200) {
          var article_content = that.data.article_content ? that.data.article_content : [];
          article_content[e.currentTarget.dataset.index] != 'undefine' ? article_content[e.currentTarget.dataset.index] = e.detail.value : article_content.push(e.detail.value);
          that.setData({
            article_content: article_content,
            text_flag: true
          });
        } else if (res.data.status == 410) {
          that.setData({
            text_flag: false
          });
          $Toast({
            content: res.data.err,
            type: 'error'
          });
        }
      }
    });
  },

  add_article: function() {
    if (this.data.article_content.length != this.data.article_img.length) {
      $Toast({
        content: '请输入上一段正文!',
        type: 'error'
      });
    } else {
      var article_img = this.data.article_img;
      var article_content = this.data.article_content;
      var file_type = this.data.file_type;
      article_img.push('/images/plus.png');
      article_content.push('');
      file_type.push(1);
      this.setData({
        article_img: article_img,
        file_type: file_type
      });
    }
  },

  delArticle: function(e) {
    var delactions = [{
      text: '删除',
      value: 1
    }];

    var article_content = this.data.article_content;

    if (article_content.length == 1) {
      this.setData({
        error: '文章至少需要包含一个段落'
      });
    } else {
      this.setData({
        isShowDelSheet: true,
        delactions: delactions,
        article_index: e.currentTarget.dataset.index
      });
    }
  },

  delArticleSheet: function(e) {
    var article_content = this.data.article_content;
    var article_img = this.data.article_img;
    var file_type = this.data.file_type;

    article_content.splice(this.data.article_index, 1);
    article_img.splice(this.data.article_index, 1);
    file_type.splice(this.data.article_index, 1);

    this.setData({
      isShowDelSheet: false,
      article_content: article_content,
      article_img: article_img,
      file_type: file_type
    });
  },

  show_article: function() {
    var that = this;
    if (!this.data.content.title || !this.data.content.author || !this.data.content.labels || this.data.article_img[0] == '/images/plus.png' || !this.data.article_content || !this.data.content.openid || this.data.article_content.length != this.data.article_img.length) {
      $Toast({
        content: '参数不全!',
        type: 'error'
      });
    } else {
      var param = {
				title: this.data.content.title,
				author: this.data.content.author,
				labels: this.data.content.labels,
				main_pic: this.data.article_img[0],
				openid: this.data.content.openid,
				gist: this.data.article_content[0]
			};

			//将输入文本手动转化成html，设置div的class支持MD插件美化
			var content = '<div class="markdown-text">';
			var count = 0;
			this.data.article_content.forEach(article => {   
				if (article != '') {
					//使用p标签将每一段内容包住
					content = content + '<p>' + article + '</p>'
				}

				//如果本段文本有插入图片，则使用img标签插入图片
				if (that.data.article_img[count] != '/images/plus.png' && that.data.file_type[count] == 1) {
					content = content + '<p><img src="' + that.data.article_img[count] + '"></p>'
				}

				//如果本段文本有插入视频，则使用video标签插入视频
				if (that.data.article_img[count] != '/images/plus.png' && that.data.file_type[count] == 2) {
					content = content + '<p><video src="' + that.data.article_img[count] + '"></p>'
				}

				count++;
			});

			content += '</div>'
			param.content = content;

			//将数据存入缓存
			wx.setStorage({
				key: 'showContent',
				data: param,
			});

			//跳转预览界面预览
			wx.navigateTo({
				url: '/pages/showcontent/showcontent',
			});
    }
  },

  submit_article: function() {
    var that = this;
    if (!this.data.content.title || !this.data.content.author || !this.data.content.labels || this.data.article_img[0] == '/images/plus.png' || !this.data.article_content || !this.data.content.openid) {
      $Toast({
        content: '参数不全!',
        type: 'error'
      });
    } else {
      clearInterval(interval);

			var file_type1 = this.data.file_type || [];
			for (var i = 0; i < this.data.article_img.length; i++) {
				if (!file_type1[i]) {
					file_type1.push(1);
				}
			}
			
			this.setData({ file_type: file_type1 });

			var param = {
				id: this.data.content.id,
				title: this.data.content.title,
				author: this.data.content.author,
				labels: this.data.content.labels,
				main_pic: this.data.article_img[0],
				openid: this.data.content.openid,
				gist: this.data.article_content[0],
				avatar: this.data.userInfo.avatar,
			};

			var article_content = this.data.article_content.join('===');
			var article_img = this.data.article_img.join('===');
			var file_type = this.data.file_type.join('===');
			param.article_content = article_content;
			param.article_img = article_img;
			param.file_type = file_type;

			//将输入文本手动转化成html，设置div的class支持MD插件美化
			var content = '<div class="markdown-text">';
			var count = 0;
			this.data.article_content.forEach(article => {
				if (article != '') {
					//使用p标签将每一段内容包住
					content = content + '<p>' + article + '</p>'
				}

				//如果本段文本有插入图片，则使用img标签插入图片
				if (that.data.article_img[count] != '/images/plus.png' && that.data.file_type[count] == 1) {
					content = content + '<p><img src="' + that.data.article_img[count] + '"></p>'
				}

				//如果本段文本有插入视频，则使用video标签插入视频
				if (that.data.article_img[count] != '/images/plus.png' && that.data.file_type[count] == 2) {
					content = content + '<p><video src="' + that.data.article_img[count] + '"></p>'
				}

				count++;
			});

			content += '</div>'
			param.content = content;

			//如果文章id存在，则修改文章，否则更新文章
			if (this.data.content.id) {
				wx.request({
					url: util.basePath + '/article/v1/updateArticle',
					method: "post",
					data: param,
					header: {
						'content-type': 'application/json'
					},
					success(res) {
						if (res.data.status == 200) {
							if (wx.getStorageSync('alterArticle')) {
								wx.removeStorage({
									key: 'alterArticle',
									success: function (res) { },
								});
							}

							if (wx.getStorageSync('isEdit')) {
								wx.removeStorage({
									key: 'isEdit',
									success: function (res) { },
								});
							}

							$Toast({
								content: '发表成功!',
								type: 'success'
							});

							wx.reLaunch({
								url: '/pages/index/index'
							});
						} else {
							$Toast({
								content: res.data.err,
								type: 'error'
							});
						}
					}
				});
			} else {
				//进行发表文章
				wx.request({
					url: util.basePath + '/article/v1/saveContent',
					method: "post",
					data: param,
					header: {
						'content-type': 'application/json'
					},
					success(res) {
						if (res.data.status == 200) {
							$Toast({
								content: '发表成功!',
								type: 'success'
							});

							wx.reLaunch({
								url: '/pages/index/index',
							})
						} else {
							$Toast({
								content: res.data.err,
								type: 'error'
							});
						}
					}
				});
			}
    }
  }
});